package com.fulihui.wgj.auth.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.wgj.auth.service.WxEventService;
import com.fulihui.wgj.facade.request.event.AuthCallBackRequest;
import com.fulihui.wgj.facade.request.event.AuthNotifyRequest;
import com.fulihui.wgj.facade.request.event.EventNotifyRequest;
import com.fulihui.wgj.facade.request.event.GetPreAuthUrlRequest;
import com.fulihui.wgj.facade.result.event.GetPreAuthUrlResult;
import com.fulihui.wgj.facade.service.event.WxEventNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author: JY
 * @date: 2018/6/20 16:38
 */
@Service
public class WxEventServiceImpl implements WxEventService {

    private static final Logger logger = LoggerFactory.getLogger(WxEventServiceImpl.class);

    @Reference(version = "1.0.0")
    WxEventNotifyService wxEventNotifyService;

    /**
     * 授权通知
     *
     * @param request
     * @return
     */
    @Override
    public boolean authNotify(AuthNotifyRequest request) {

        //调用服务
        BaseResult result = wxEventNotifyService.authNotify(request);

        return result.getErrcode() == 0;
    }

    /**
     * 事件通知
     *
     * @param request
     * @return
     */
    @Override
    public boolean eventNotify(EventNotifyRequest request) {

        //调用服务
        BaseResult result = wxEventNotifyService.eventNotify(request);

        return result.getErrcode() == 0;
    }

    /**
     * 跳转认证Url
     *
     * @param loginId
     * @return
     */
    @Override
    public String preAuthUrl(String loginId) {

        try {
            //请求参数
            GetPreAuthUrlRequest request = new GetPreAuthUrlRequest();
            request.setLoginId(loginId);

            //调用服务
            GetPreAuthUrlResult result = wxEventNotifyService.getPreAuthUrl(request);

            logger.info("用户：{}，拿到授权地址，跳转到微信进行授权.....", loginId);

            return result.getErrcode() == 0 ? result.getAuthUrl() : null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 认证回调地址
     *
     * @param authCode
     * @return
     */
    @Override
    public boolean authCallBack(String authCode) {

        //请求参数
        AuthCallBackRequest authCallBackRequest = new AuthCallBackRequest();
        authCallBackRequest.setAuthCode(authCode);

        //调用服务
        BaseResult baseResult = wxEventNotifyService.authCallBack(authCallBackRequest);

        return baseResult.getErrcode() == 0;
    }
}
